package routes

import (
	"ticket/docs"
	"ticket/internal/handlers"
	"ticket/internal/middleware"

	"github.com/gin-contrib/sessions/memstore"

	"github.com/gin-contrib/gzip"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

func LoadRoutes(middlewares ...gin.HandlerFunc) *gin.Engine {
	docs.SwaggerInfo.Title = viper.GetString("swagger.title")
	docs.SwaggerInfo.Description = viper.GetString("swagger.desc")
	docs.SwaggerInfo.Version = "1.0"
	docs.SwaggerInfo.Host = viper.GetString("swagger.host")
	docs.SwaggerInfo.BasePath = viper.GetString("swagger.base")
	docs.SwaggerInfo.Schemes = []string{"http"}

	gin.SetMode(gin.DebugMode)

	router := gin.Default()
	router.Use(gin.Logger(), gin.Recovery(), gzip.Gzip(gzip.DefaultCompression))
	router.Use(middlewares...)

	store := memstore.NewStore([]byte(viper.GetString("jwt.secret_key")))
	store.Options(sessions.Options{
		Path:     "/",
		MaxAge:   viper.GetInt("jwt.expires"),
		HttpOnly: true,
	})
	router.Use(sessions.Sessions("session", store))

	router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	group := router.Group("/")
	{
		handlers.RegisterLoginRouter(group)
	}

	apiRouter := router.Group("/")
	apiRouter.Use(middleware.AuthMiddleware())

	userGroup := apiRouter.Group("/user")
	{
		handlers.RegisterUserRouter(userGroup)
	}

	teamGroup := apiRouter.Group("/team")
	{
		handlers.RegisterTeamRouter(teamGroup)
	}

	projectGroup := apiRouter.Group("/project")
	{
		handlers.RegisterProjectRouter(projectGroup)
	}

	taskGroup := apiRouter.Group("/task")
	{
		handlers.RegisterTaskRouter(taskGroup)
	}

	taskLogGroup := apiRouter.Group("/task_log")
	{
		handlers.RegisterTaskLogRouter(taskLogGroup)
	}

	roleGroup := apiRouter.Group("/role")
	{
		handlers.RegisterRoleRouter(roleGroup)
	}

	return router
}
